package com.tmpt.controller.action;

import com.opensymphony.xwork2.ActionSupport;
import com.tmpt.dto.A1OperationlogDto;
import com.tmpt.dto.A2UserDto;
import com.tmpt.dto.Result;
import com.tmpt.others.singleuser.OnlineUserBindingListener;
import com.tmpt.others.singleuser.Userinfo;
import com.tmpt.service.ILoginFailureService;
import com.tmpt.service.IOperationlogService;
import com.tmpt.service.IOrgService;
import com.tmpt.service.ISecurityV2Service;
import com.tmpt.utils.DateTool;
import com.tmpt.utils.MD5Util;
import com.tmpt.utils.WebUtils;
import com.tmpt.utils.rsa.DecodeAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

@Controller
@Scope("prototype")
public class EmpAction extends ActionSupport{
	private Logger log = Logger.getLogger(this.getClass());
	
	private long empId;
	private String loginname;
	private String username;
	private String password;
	private String name;
	private int sex;
	private String email;
	private String telephone;
	private long deptId;
	private String validateCode;
	private String result;
	private String showMode;//desktop,menu
	private String passwordKeyboard;

	private String oldPassword;
	
	private A1OperationlogDto oprDtoBack = new A1OperationlogDto(WebUtils.getRequest(), A1OperationlogDto.UserTypeBack);
	@Resource private ILoginFailureService loginFailureService;
	@Resource private IOperationlogService operationlogService;
	@Resource private ISecurityV2Service securityV2Service;
	@Resource private IOrgService orgService;
	
	
    public static final String VALIDATE_CODE = "validateCode";  
	
    
    /**
	 * 用户登录
	 * @return
	 */
	public String login(){
		try {
			oprDtoBack.setLogTypeName("登录[后台]");

			//判断用户是否已登录
			/*
			{
				HttpSession session = WebUtils.getRequest().getSession();
				ServletContext application = session.getServletContext();
				List<Userinfo> onlineUserList = (List<Userinfo>)application.getAttribute("onlineUserList");
				if(onlineUserList!=null){
					for(Userinfo userinfo: onlineUserList){
						if(
								userinfo.getUsername().equals(this.username)
								//&& DateTool.compare2CurDateMinuter(userinfo.getLastAccessTime(), 1)==1
							)
						{
							this.result = "该用户已登录";
							oprDtoBack.setDescription("登录名:"+username+":"+this.result);
							operationLogService.addOperationlog(oprDtoBack);
							return "indexBefore1";
						}
					}
				}
			}
			*/

			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();
	        String username = this.username;
	        String password = this.password;
	        
			//6次登录密码错误，锁定1小时
			int hourInt =1;
			int limitFailureTimes=6;
			
	        //检测验证码  
			Object isLoginSuccessBack = session.getAttribute("isLoginSuccessBack");
			if(isLoginSuccessBack!=null){
				if(!isValidateCodeOK(request)){
					this.result = "验证码错误！";
					oprDtoBack.setDescription("登录名:"+username+":"+this.result);
					operationlogService.addOperationlog(oprDtoBack);
					return "indexBefore1";
				}
			}
	          
	        String passwordNoEncode = "";
	        String psdMd5 = "";
	        try {
	        	//解密
	    		DecodeAction decodeAction = new DecodeAction();
	    		password = decodeAction.execute(password);
	    		passwordNoEncode = password;
	    		//password by md5 for store
	        	psdMd5 = password+username;
	    		//log.debug("psdMd5:"+psdMd5);
	        	psdMd5 = MD5Util.toMD5ForApp(psdMd5);
	    		//log.debug("psdMd5:"+psdMd5);
			} catch (Exception e) {
				e.printStackTrace();
				this.result = "密码加解密出错！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationlogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
	    	
	        //验证用户账号与密码是否对应  
			A2UserDto empDto = securityV2Service.getUserByLoginname(username);
			if(empDto == null){
				this.result = "用户名不存在！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationlogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
			if(empDto.getDeleteFlag() == 1){
				this.result = "用户状态不正常！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationlogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
			

			//登录次数限制-开始
			Result resultLoginLimit = loginFailureService.loginBefore(0, empDto.getId(),0, hourInt, limitFailureTimes);
			if(!resultLoginLimit.isSuccess()){
				this.result = resultLoginLimit.getContentOnly();
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationlogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}

	        if(!empDto.getPassword().toLowerCase().equals(psdMd5.toLowerCase())) {
	        	session.setAttribute("isLoginSuccessBack", -1);

				//登录次数限制-密码错误
				resultLoginLimit = loginFailureService.loginFailure(0, empDto.getId(),0, hourInt, limitFailureTimes);
				if(!resultLoginLimit.isSuccess()){
					this.result = "密码不正确";
					oprDtoBack.setDescription("登录名:"+username+":"+this.result);
					operationlogService.addOperationlog(oprDtoBack);
					return "indexBefore1";
				}

				this.result = "密码不正确；"+resultLoginLimit.getContentOnly();
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationlogService.addOperationlog(oprDtoBack);
				
				return "indexBefore1";
	        }  
	        
			//login success , release data about the customer
			loginFailureService.loginRelease(0, empDto.getId(),0);
	          
	        //UsernamePasswordAuthenticationToken实现 Authentication  
	        //UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, psdMd5.toLowerCase());
	        // Place the last username attempted into HttpSession for views  
	          
	        this.email = empDto.getEmail();
			long userId = empDto.getId();
	        session.setAttribute("username", this.username);
	        session.setAttribute("userFullName", empDto.getName());
	        session.setAttribute("userId", userId);
	        session.setAttribute("password", passwordNoEncode);
	        session.setAttribute("showMode", showMode);
	        session.setAttribute("companyId", empDto.getCompanyId());
	        final String toEmail = empDto.getEmail();
	        
	        //Send Email for validate
	        final String randStr = this.genRandStr(6);
	        session.setAttribute("randStr", randStr);
	        
	        /*
	        new Thread(new Runnable() {
				@Override
				public void run() {
					 SendMail.sendMailTo(toEmail,"登录系统校验码", "校验码："+randStr+"; 您请求身份验证，任何人以任何方式向您索取校验码，均为诈骗行为，请勿泄露。");
				}
			}).start();
			*/
	       
	        this.result="用户名、密码校验正确";
			oprDtoBack.setDescription("登录名:"+username+":"+this.result);
			operationlogService.addOperationlog(oprDtoBack);

			//init 岗位下级员工
			orgService.initPostUser(userId);
			
			return "indexBefore2";
			//return "index";
		} catch (Exception e) {
			e.printStackTrace();
			this.result = e.getLocalizedMessage();
			return "indexBefore1";
		}
	}





	private String genRandStr(int count){
		Random random = new Random();
		String dataSourceStr = "0123456789";
		String sRand="";

		for (int i=0;i<count;i++){
		    int index = random.nextInt(dataSourceStr.length());
			char dataChar = dataSourceStr.charAt(index);
			String rand = String.valueOf(dataChar);
		    sRand+=rand;
		}
		
		return sRand;
	}

	/**
	 * 重置密码
	 * @return
	 */
	public String resetPassword(){
		Result resultObj = new Result();
		try{
			System.out.println("----resetPassword------"+username);
			String psdMd5 = password+username;
			psdMd5 = MD5Util.toMD5ForApp(psdMd5);
			System.out.println("----resetPassword------"+psdMd5);

			resultObj = securityV2Service.resetPassword(empId, psdMd5);
		}catch (Exception e){
			resultObj.fault(e.getLocalizedMessage());
			e.printStackTrace();
		}
		this.result = resultObj.getContent();
		return "jsonResult";
	}


    private boolean isValidateCodeOK(HttpServletRequest request) {   
        HttpSession session = request.getSession();  
          
        Object obj = session.getAttribute(VALIDATE_CODE); 
        String sessionValidateCode = (null == obj ? "" : obj.toString());  
        //让上一次的验证码失效  
        session.setAttribute(VALIDATE_CODE, null);  
        String validateCodeParameter = this.validateCode;    
        if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {    
        	//throw new AuthenticationServiceException("验证码错误！");
        	return false;
        }    
        return true;
    }  
	
    
    
    /**
	 * 电子邮箱校验
	 * @return
	 */
	public String emailValidate(){
		oprDtoBack.setLogTypeName("登录[后台]");
		try {
			HttpServletRequest request = WebUtils.getRequest();
			HttpSession session = request.getSession();
			String emailValidateCode = this.validateCode;
			String emailValidateCodeSession = (String)session.getAttribute("randStr");
			
			/*
			if(!emailValidateCode.equalsIgnoreCase(emailValidateCodeSession)){
				this.result = "电子邮箱校验码错误，请重新登录！";
				oprDtoBack.setDescription("登录名:"+username+":"+this.result);
				operationLogService.addOperationlog(oprDtoBack);
				return "indexBefore1";
			}
			*/
			
			//登录成功
			session.setAttribute("onlineUserBindingListener", new OnlineUserBindingListener(username));
			return "index";
		} catch (Exception e) {
			e.printStackTrace();
			this.result = e.getLocalizedMessage();
			oprDtoBack.setDescription("登录名:"+username+":"+this.result);
			operationlogService.addOperationlog(oprDtoBack);
			return "indexBefore1";
		}
	}
    
	
	public String singleUser(){
		Result result = new Result();
		try {
			HttpSession session = WebUtils.getRequest().getSession();
			ServletContext application = session.getServletContext();
			List<Userinfo> onlineUserList = (List<Userinfo>)application.getAttribute("onlineUserList");
			String username = (String)session.getAttribute("username");
			if(onlineUserList!=null){
				for(Userinfo userinfo: onlineUserList){
					if(userinfo.getUsername().equals(username)){
						userinfo.setLastAccessTime(DateTool.getCurrentDatetime());
					}
				}
			}
		} catch (Exception e) {
			result.fault("系统出错:"+e.getLocalizedMessage());
			this.result = JSONObject.fromObject(result.getResultMap()).toString();
		}
		return "jsonResult";
	}
    
	
	
	public long getEmpId() {
		return empId;
	}
	public void setEmpId(long empId) {
		this.empId = empId;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public long getDeptId() {
		return deptId;
	}
	public void setDeptId(long deptId) {
		this.deptId = deptId;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	public String getValidateCode() {
		return validateCode;
	}
	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	public String getOldPassword() {
		return oldPassword;
	}
	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}
	public Logger getLog() {
		return log;
	}
	public void setLog(Logger log) {
		this.log = log;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public A1OperationlogDto getOprDtoBack() {
		return oprDtoBack;
	}
	public void setOprDtoBack(A1OperationlogDto oprDtoBack) {
		this.oprDtoBack = oprDtoBack;
	}
	public String getShowMode() {
		return showMode;
	}
	public void setShowMode(String showMode) {
		this.showMode = showMode;
	}
	public ILoginFailureService getLoginFailureService() {
		return loginFailureService;
	}
	public void setLoginFailureService(ILoginFailureService loginFailureService) {
		this.loginFailureService = loginFailureService;
	}
	public ISecurityV2Service getSecurityV2Service() {
		return securityV2Service;
	}
	public void setSecurityV2Service(ISecurityV2Service securityV2Service) {
		this.securityV2Service = securityV2Service;
	}

	public String getPasswordKeyboard() {
		return passwordKeyboard;
	}

	public void setPasswordKeyboard(String passwordKeyboard) {
		this.passwordKeyboard = passwordKeyboard;
	}

	public static String getVALIDATE_CODE() {
		return VALIDATE_CODE;
	}

	public IOperationlogService getOperationlogService() {
		return operationlogService;
	}

	public void setOperationlogService(IOperationlogService operationlogService) {
		this.operationlogService = operationlogService;
	}
}
